package com.cskaoyan.utils;

import com.cskaoyan.Demo;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.apache.commons.dbcp.PoolingDataSource;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 创建日期: 2022/07/28 11:33
 *
 * @author ciggar
 */
public class DBCPUtils {

    static DataSource dataSource;

    static {
        try {
            // 初始化Datasource
            Properties properties = new Properties();
//            properties.load(new FileInputStream("src/main/resources/dbcp.properties"));

            // APPClassLoader
            ClassLoader classLoader = DBCPUtils.class.getClassLoader();


//            URL url = classLoader.getResource("dbcp.properties");
//            String path = url.getPath();
//            System.out.println("path:" + path);
//            FileInputStream fileInputStream = new FileInputStream(path);
//            properties.load(fileInputStream);

            InputStream in = classLoader.getResourceAsStream("dbcp.properties");
            properties.load(in);


            dataSource = BasicDataSourceFactory.createDataSource(properties);

        }catch (Exception ex) {
            ex.printStackTrace();
        }

    }





    // 获取连接的方法
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
}
